import Vue from 'vue'
import axios from 'axios'

// 基于portal的配置
function setHttpConfig (config) {
    // 从config中读取作用域，并设置baseURL
    if (!Vue.prototype.isPortal || !window.apiConfig) {
        return
    }
    if (config.scopeName && window.apiConfig[config.scopeName]) {
        config['baseURL'] = window.apiConfig[config.scopeName].ip
    }
}

function setHttpHeader (config, prefix) {
    setHttpConfig(config)
    if (!prefix) {
        return
    }

    // 接口api处理（从云服务进来的接口，带上云服务前缀prefix）
    const url = config.url
    if (url.startsWith('http')) {
        const httpUrl = new URL(url)
        config.url = prefix + httpUrl.pathname
    } else if (url.startsWith('/')) {
        config.url = prefix + url
    } else {
        config.url = prefix + '/' + url
    }
}

export default function (router, store, config = {}) {
    let httpConfig = {
        timeout: 5000,
        baseURL: process.env.http_base_url,
        headers: { 'content-type': 'application/x-www-form-urlencoded' },
        withCredentials: true
    }
    Object.assign(httpConfig, config)
    const http = axios.create(httpConfig)

    // http interceptor for request
    http.interceptors.request.use(function (config) {
        // Do something before request is sent
        setHttpHeader(config, store.state.organization)
        return config
    }, function (error) {
        return Promise.reject(error)
    })

    // 拦截response
    http.interceptors.response.use(response => {
        if (response.status !== 200) {
            return Promise.reject(new Error('request failed'))
        }

        const result = response.data
        // cookie过期则跳转至登录页面
        if (result.code === 'login') {
            if (result.data) {
                if (result.data.login_url) {
                    const paths = window.location.pathname.split('/')
                    if (paths.length > 3) {
                        let href = router.resolve({
                            path: '/login',
                            query: { path: window.location.href, appId: result.data.app_id }
                        })
                        window.top.location.href = window.location.origin + '/' + paths[1] + '/' + 'auth/' + href.href
                    } else {
                        let href = router.resolve({
                            path: '/login',
                            query: { path: window.location.href, appId: result.data.app_id }
                        })
                        window.top.location.href = result.data.login_url + '/' + 'auth/' + href.href
                    }
                } else {
                    router.push('/404')
                }
            } else {
                router.push('/404')
            }

            return Promise.reject(result.info)
        }

        let res = {}
        let httpBody = {}
        const dataKeys = ['data', 'code', 'info', 'headers']
        const allKeys = Object.keys(result)

        dataKeys.forEach(function (key) {
            if (allKeys.indexOf(key) > -1) {
                res[key] = result[key]
            } else if (key in response) {
                res[key] = response[key]
            }
        })

        allKeys.forEach(key => {
            if (dataKeys.indexOf(key) === -1) {
                httpBody[key] = result[key]
            }
        })

        Object.keys(httpBody).length > 0 && store.commit('updateRequestBody', httpBody)

        return res
    }, error => {
        return Promise.reject(error)
    })

    function _get (url, succ, fail, config = {}) {
        http.get(url, config)
            .then(function (response) {
                typeof succ === 'function' && succ(response)
            })
            .catch(function (error) {
                console.error(url + ' failed, error messsage: ' + error)
                typeof fail === 'function' && fail()
            })
    }

    function _delete (url, succ, fail, config = {}) {
        http.delete(url, config)
            .then(function (response) {
                typeof succ === 'function' && succ(response)
            })
            .catch(function (error) {
                console.error(url + ' failed, error messsage: ' + error)
                typeof fail === 'function' && fail()
            })
    }

    function _post (url, param, succ, fail, config = {}) {
        http.post(url, param, config)
            .then(function (response) {
                typeof succ === 'function' && succ(response)
            })
            .catch(function (error) {
                console.error(url + ' failed, error messsage: ' + error)
                typeof fail === 'function' && fail()
            })
    }

    function _put (url, param, succ, fail, config = {}) {
        http.put(url, param, config)
            .then(function (response) {
                typeof succ === 'function' && succ(response)
            })
            .catch(function (error) {
                console.error(url + ' failed, error messsage: ' + error)
                typeof fail === 'function' && fail()
            })
    }

    function _getLogo (succ, fail, config = {}) {
        _get(`api/config/get_app_logo/${store.state.organization}`, succ, fail, config)
    }

    function _getLogoTitle (succ, fail, config = {}) {
        _get(`api/config/get_app_logo/title/${store.state.organization}`, succ, fail, config)
    }

    Vue.prototype.$mg_get = _get
    Vue.prototype.$mg_delete = _delete
    Vue.prototype.$mg_post = _post
    Vue.prototype.$mg_put = _put
    Vue.prototype.$logo = _getLogo
    Vue.prototype.$logo_title = _getLogoTitle
}
